package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.domain.dto.farmer.FlowerDetailDTO;
import com.flower.domain.entity.FlowerCulture;
import com.flower.domain.entity.FlowerImage;
import com.flower.mapper.FlowerCultureMapper;
import com.flower.mapper.FlowerEncyclopediaMapper;
import com.flower.mapper.FlowerGrowingEnvironmentMapper;
import com.flower.mapper.FlowerImageMapper;
import com.flower.service.FlowerCultureService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 花卉文化服务实现类
 */
@Service
@RequiredArgsConstructor
public class FlowerCultureServiceImpl extends ServiceImpl<FlowerCultureMapper, FlowerCulture> implements FlowerCultureService {

    private final FlowerEncyclopediaMapper encyclopediaMapper;
    private final FlowerGrowingEnvironmentMapper environmentMapper;
    private final FlowerImageMapper imageMapper;
    private final FlowerCultureMapper flowerCultureMapper;

    @Override
    public List<FlowerDetailDTO> getFlowerList() {
        List<FlowerDetailDTO> flowerList = flowerCultureMapper.selectFlowerList();
        
        // 如果列表为空，直接返回
        if (flowerList == null || flowerList.isEmpty()) {
            return flowerList;
        }
        
        // 获取所有花卉ID
        List<Long> flowerIds = flowerList.stream()
                .map(FlowerDetailDTO::getId)
                .toList();
                
        // 批量查询花卉图片
        LambdaQueryWrapper<FlowerImage> imageWrapper = Wrappers.lambdaQuery(FlowerImage.class)
                .in(FlowerImage::getEncyclopediaId, flowerIds)
                .orderByAsc(FlowerImage::getSortOrder);
        List<FlowerImage> allImages = imageMapper.selectList(imageWrapper);
        
        // 按花卉ID分组
        Map<Long, List<FlowerImage>> imageMap = allImages.stream()
                .collect(Collectors.groupingBy(FlowerImage::getEncyclopediaId));
        
        // 为每个花卉DTO设置图片信息
        for (FlowerDetailDTO flower : flowerList) {
            List<FlowerImage> images = imageMap.getOrDefault(flower.getId(), new ArrayList<>());
            
            // 设置图片列表
            List<String> imageUrls = images.stream()
                    .map(FlowerImage::getImageUrl)
                    .collect(Collectors.toList());
            flower.setImages(imageUrls);
            
            // 设置主图
            images.stream()
                    .filter(img -> Integer.valueOf(1).equals(img.getIsMain()))
                    .findFirst()
                    .ifPresent(mainImg -> flower.setImage(mainImg.getImageUrl()));
            
            // 如果没有设置主图，但有图片，则使用第一张作为主图
            if (flower.getImage() == null && !imageUrls.isEmpty()) {
                flower.setImage(imageUrls.get(0));
            }
            
            // 确保缩略图存在
            if (flower.getThumbnail() == null && flower.getImage() != null) {
                flower.setThumbnail(flower.getImage());
            }
        }
        
        return flowerList;
    }

    @Override
    public FlowerDetailDTO getFlowerDetail(Long id) {
        FlowerDetailDTO flower = flowerCultureMapper.selectFlowerDetail(id);
        
        if (flower == null) {
            return null;
        }
        
        // 查询花卉图片
        LambdaQueryWrapper<FlowerImage> imageWrapper = Wrappers.lambdaQuery(FlowerImage.class)
                .eq(FlowerImage::getEncyclopediaId, id)
                .orderByAsc(FlowerImage::getSortOrder);
        List<FlowerImage> images = imageMapper.selectList(imageWrapper);
        
        // 设置图片列表
        List<String> imageUrls = images.stream()
                .map(FlowerImage::getImageUrl)
                .collect(Collectors.toList());
        flower.setImages(imageUrls);
        
        // 设置主图
        images.stream()
                .filter(img -> Integer.valueOf(1).equals(img.getIsMain()))
                .findFirst()
                .ifPresent(mainImg -> flower.setImage(mainImg.getImageUrl()));
        
        // 如果没有设置主图，但有图片，则使用第一张作为主图
        if (flower.getImage() == null && !imageUrls.isEmpty()) {
            flower.setImage(imageUrls.get(0));
        }
        
        // 确保缩略图存在
        if (flower.getThumbnail() == null && flower.getImage() != null) {
            flower.setThumbnail(flower.getImage());
        }
        
        return flower;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void incrementViewCount(Long id) {
        flowerCultureMapper.incrementViewCount(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateCulture(FlowerCulture flowerCulture) {
        // 先检查是否已存在记录
        FlowerCulture existCulture = lambdaQuery()
                .eq(FlowerCulture::getEncyclopediaId, flowerCulture.getEncyclopediaId())
                .one();
        
        if (existCulture != null) {
            // 存在则设置ID并更新
            flowerCulture.setId(existCulture.getId());
            return updateById(flowerCulture);
        } else {
            // 不存在则新增
            return save(flowerCulture);
        }
    }

    @Override
    public FlowerCulture getFlowerCulture(Long encyclopediaId) {
        return lambdaQuery()
                .eq(FlowerCulture::getEncyclopediaId, encyclopediaId)
                .select(FlowerCulture::getId, 
                       FlowerCulture::getEncyclopediaId,
                       FlowerCulture::getFlowerLanguage,
                       FlowerCulture::getPoetry,
                       FlowerCulture::getCulturalMeaning,
                       FlowerCulture::getLiteraryQuotations,
                       FlowerCulture::getCreateTime,
                       FlowerCulture::getUpdateTime)
                .one();
    }

    @Override
    public List<FlowerDetailDTO> searchFlowers(String keyword) {
        List<FlowerDetailDTO> flowerList = flowerCultureMapper.searchFlowers(keyword);

        // 如果列表为空，直接返回
        if (flowerList == null || flowerList.isEmpty()) {
            return flowerList;
        }

        // 获取所有花卉ID
        List<Long> flowerIds = flowerList.stream()
                .map(FlowerDetailDTO::getId)
                .toList();

        // 批量查询花卉图片
        LambdaQueryWrapper<FlowerImage> imageWrapper = Wrappers.lambdaQuery(FlowerImage.class)
                .in(FlowerImage::getEncyclopediaId, flowerIds)
                .orderByAsc(FlowerImage::getSortOrder);
        List<FlowerImage> allImages = imageMapper.selectList(imageWrapper);

        // 按花卉ID分组
        Map<Long, List<FlowerImage>> imageMap = allImages.stream()
                .collect(Collectors.groupingBy(FlowerImage::getEncyclopediaId));

        // 为每个花卉DTO设置图片信息
        for (FlowerDetailDTO flower : flowerList) {
            List<FlowerImage> images = imageMap.getOrDefault(flower.getId(), new ArrayList<>());

            // 设置图片列表
            List<String> imageUrls = images.stream()
                    .map(FlowerImage::getImageUrl)
                    .collect(Collectors.toList());
            flower.setImages(imageUrls);

            // 设置主图
            images.stream()
                    .filter(img -> Integer.valueOf(1).equals(img.getIsMain()))
                    .findFirst()
                    .ifPresent(mainImg -> flower.setImage(mainImg.getImageUrl()));

            // 如果没有设置主图，但有图片，则使用第一张作为主图
            if (flower.getImage() == null && !imageUrls.isEmpty()) {
                flower.setImage(imageUrls.get(0));
            }

            // 确保缩略图存在
            if (flower.getThumbnail() == null && flower.getImage() != null) {
                flower.setThumbnail(flower.getImage());
            }
        }

        return flowerList;
    }

    /**
     * 根据百科ID判断文化信息是否存在
     *
     * @param encyclopediaId 百科ID
     * @return 是否存在
     */
    @Override
    public boolean existsByEncyclopediaId(Long encyclopediaId) {
        return lambdaQuery()
                .eq(FlowerCulture::getEncyclopediaId, encyclopediaId)
                .exists();
    }

    /**
     * 根据百科ID删除文化信息
     *
     * @param encyclopediaId 百科ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByEncyclopediaId(Long encyclopediaId) {
        return lambdaUpdate()
                .eq(FlowerCulture::getEncyclopediaId, encyclopediaId)
                .remove();
    }

    /**
     * 批量更新文化信息状态（已废弃）
     *
     * @param ids 百科ID列表
     * @param status 状态值
     * @return 是否成功
     * @deprecated 数据库中不存在status字段，此方法已废弃
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Deprecated
    public boolean updateStatusBatch(List<Long> ids, Integer status) {
        // 数据库中没有status字段，方法已废弃
        return false;
    }

    /**
     * 根据百科ID查询文化信息列表
     *
     * @param encyclopediaIds 百科ID列表
     * @return 文化信息列表
     */
    @Override
    public List<FlowerCulture> listByEncyclopediaIdsAndStatus(List<Long> encyclopediaIds, Integer status) {
        return lambdaQuery()
                .in(encyclopediaIds != null && !encyclopediaIds.isEmpty(), FlowerCulture::getEncyclopediaId, encyclopediaIds)
                .orderByDesc(FlowerCulture::getUpdateTime)
                .list();
    }

    /**
     * 高级查询花卉文化信息
     *
     * @param keyword 关键词
     * @param hasPoetry 是否包含诗词
     * @param hasLiteraryQuotations 是否包含文学典故
     * @return 文化信息列表
     */
    @Override
    public List<FlowerCulture> advancedSearch(String keyword, Boolean hasPoetry, Boolean hasLiteraryQuotations) {
        LambdaQueryWrapper<FlowerCulture> wrapper = Wrappers.lambdaQuery();
        
        // 构建关键词条件
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(w -> w
                    .like(FlowerCulture::getFlowerLanguage, keyword)
                    .or()
                    .like(FlowerCulture::getPoetry, keyword)
                    .or()
                    .like(FlowerCulture::getCulturalMeaning, keyword)
                    .or()
                    .like(FlowerCulture::getLiteraryQuotations, keyword)
            );
        }
        
        // 构建诗词条件
        if (hasPoetry != null) {
            if (hasPoetry) {
                wrapper.isNotNull(FlowerCulture::getPoetry)
                       .ne(FlowerCulture::getPoetry, "");
            } else {
                wrapper.and(w -> w
                        .isNull(FlowerCulture::getPoetry)
                        .or()
                        .eq(FlowerCulture::getPoetry, "")
                );
            }
        }
        
        // 构建文学典故条件
        if (hasLiteraryQuotations != null) {
            if (hasLiteraryQuotations) {
                wrapper.isNotNull(FlowerCulture::getLiteraryQuotations)
                       .ne(FlowerCulture::getLiteraryQuotations, "");
            } else {
                wrapper.and(w -> w
                        .isNull(FlowerCulture::getLiteraryQuotations)
                        .or()
                        .eq(FlowerCulture::getLiteraryQuotations, "")
                );
            }
        }
        
        wrapper.orderByDesc(FlowerCulture::getUpdateTime);
        
        return list(wrapper);
    }
} 